package com.retail.order.controller;

import com.alibaba.fastjson.JSON;
import com.retail.common.core.domain.Result;
import com.retail.order.domain.OrderSku;
import com.retail.order.config.RabbitMQConfig;
import com.retail.order.domain.Take;
import com.retail.order.service.OrderSkuService;
import com.retail.order.vo.OrderRequest;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import com.retail.shopping.common.domain.response.CartListResponse;
import com.retail.shopping.remote.ProductFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/orderSku")
public class OrderSkuController {
    @Autowired
    private OrderSkuService orderSkuService;


    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private final String address="CART_USER_ID_";

    private final String redisKey = "SHOPPING_CART:";

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostMapping("/getOrderId")
    public Result getOrderId(@RequestBody OrderRequest orderRequest){
        rabbitTemplate.convertAndSend (RabbitMQConfig.INSERT_EXCHANGE,RabbitMQConfig.INSERT_KEY,orderRequest,message -> {
            message.getMessageProperties ().setMessageId (UUID.randomUUID ().toString ());
            return message;
        },new CorrelationData (UUID.randomUUID ().toString ()));
        return Result.success();
    }

    @GetMapping("/getOrderResponse")
    public Result getOrderResponse(@RequestParam String uuid){
        return orderSkuService.getOrderRespone(uuid);
    }

    @PostMapping("/getUserTake")
    public Result<List<Take>> getUserTake(@RequestParam("userId") Integer userId){
        return Result.success (orderSkuService.getUserTake(userId));
    }

    @PostMapping("/getCartOrderList")
    public Result<List<CartListResponse>> getCartOrderList(@RequestParam("orderId")String orderId,@RequestParam("userId")Integer userId){
        List<OrderSku> listResponses = orderSkuService.getCartOrderList(orderId);
        String key = redisKey+address+userId;
        BoundHashOperations<String, Object, Object> cartMap = redisTemplate.boundHashOps (key);
        //需要获得一个商品的单价商品的数量商品的名称
        ArrayList<CartListResponse> cartListResponses = new ArrayList<> ();
        for (OrderSku listRespons : listResponses) {
            String cart= (String) cartMap.get (listRespons.getSkuId () + "");
            CartListResponse cartListResponse = JSON.parseObject (cart, CartListResponse.class);
            cartListResponses.add (cartListResponse);
        }
        return Result.success (cartListResponses);
    }




}

